<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑作业' : '创建作业'"
    width="680px"
    :before-close="handleClose"
    class="assignment-dialog"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="assignment-form"
    >
      <!-- 基本信息区块 -->
      <div class="form-section">
        <div class="section-title">基本信息</div>
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="form.title"
            placeholder="请输入作业标题"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入作业描述"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="截止日期" prop="due_date">
              <el-date-picker
                v-model="form.due_date"
                type="datetime"
                placeholder="选择截止日期"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledDate"
                class="w-full"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="满分" prop="score">
              <el-input-number
                v-model="form.score"
                :min="0"
                :max="100"
                :step="5"
                class="w-full"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 互评设置区块 -->
      <div class="form-section" v-if="isEdit">
        <div class="section-title">互评设置</div>
        <el-form-item label="开启作业互评">
          <el-switch
            v-model="form.is_peer_review_enabled"
            @change="handlePeerReviewChange"
            active-color="#409EFF"
          />
        </el-form-item>

        <template v-if="form.is_peer_review_enabled">
          <el-form-item label="互评截止日期" prop="peer_review_due_date">
            <el-date-picker
              v-model="form.peer_review_due_date"
              type="datetime"
              placeholder="选择互评截止日期"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              :disabled-date="disabledPeerReviewDate"
              class="w-full"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="互评份数" prop="peer_review_count">
            <el-input-number
              v-model="form.peer_review_count"
              :min="0"
              :max="maxPeerReviewCount"
              :step="1"
            >
              <template #suffix>份</template>
            </el-input-number>
            <div class="info-box" :class="{ 'warning': submissionCount === 0 }">
              <el-icon><InfoFilled /></el-icon>
              <span v-if="submissionCount > 0">
                当前已有 {{ submissionCount }} 份提交，每个学生最多可评价 {{ maxPeerReviewCount}} 份作业
              </span>
              <span v-else>
                当前还没有学生提交作业，互评份数将在有学生提交后自动调整
              </span>
            </div>
          </el-form-item>
        </template>
      </div>

      <!-- 附件上传区块 -->
      <div class="form-section">
        <div class="section-title">附件资料</div>
        <el-form-item label="上传附件">
          <el-upload
            class="assignment-upload"
            :action="uploadAction"
            :auto-upload="false"
            :file-list="fileList"
            multiple
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
          >
            <el-button type="primary" class="upload-btn">
              <el-icon class="mr-2"><Upload /></el-icon>
              选择文件
            </el-button>
            <template #tip>
              <div class="upload-tip">
                <el-icon><Warning /></el-icon>
                支持常见文档格式，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import {ElMessage} from "element-plus";

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  form: {
    type: Object,
    required: true
  },
  isEdit: {
    type: Boolean,
    required: true
  },
  fileList: {
    type: Array,
    required: true
  },
  submissionStats: { // 新增属性
    type: Object,
    default: () => ({
      total: 0,
      submitted: 0
    })
  }
})

const emit = defineEmits(['update:visible', 'close', 'submit', 'update:file-list'])

const formRef = ref(null)
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 计算提交人数和最大互评份数
const submissionCount = computed(() => props.submissionStats.submitted || 0)
const maxPeerReviewCount = computed(() => {
  const count = submissionCount.value - 1
  return count > 0 ? count : 0
})

// 监听提交人数变化，动态调整互评份数
watch(submissionCount, (newCount) => {
  if (props.form.is_peer_review_enabled && props.form.peer_review_count > maxPeerReviewCount.value) {
    props.form.peer_review_count = maxPeerReviewCount.value
  }
})

// 表单验证规则
const rules = {
  peer_review_due_date: [
    {
      validator: (rule, value, callback) => {
        if (props.form.is_peer_review_enabled) {
          if (!value) {
            callback(new Error('请选择互评截止日期'))
          } else if (new Date(value) <= new Date(props.form.due_date)) {
            callback(new Error('互评截止日期必须晚于作业截止日期'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: ['change', 'blur']
    }
  ],
  peer_review_count: [
    {
      validator: (rule, value, callback) => {
        if (value > maxPeerReviewCount.value) {
          callback(new Error(`互评份数不能超过${maxPeerReviewCount.value}份`))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

const handlePeerReviewChange = (value) => {
  // 检查是否已过作业截止日期
  const now = new Date()
  const dueDate = new Date(props.form.due_date)

  if (value && now < dueDate) {
    ElMessage.warning('只能在作业截止后开启互评')
    props.form.is_peer_review_enabled = false
    return
  }

  props.form.is_peer_review_enabled = Boolean(value)

  if (props.form.is_peer_review_enabled) {
    const defaultCount = Math.min(2, maxPeerReviewCount.value)
    props.form.peer_review_count = defaultCount
    // 设置默认互评截止时间为作业截止日期后7天
    const defaultPeerReviewDueDate = new Date(props.form.due_date)
    defaultPeerReviewDueDate.setDate(defaultPeerReviewDueDate.getDate() + 7)
    props.form.peer_review_due_date = defaultPeerReviewDueDate.toISOString().slice(0, 19).replace('T', ' ')
  } else {
    props.form.peer_review_count = null
    props.form.peer_review_due_date = null
  }
}

const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 不能选择今天之前的日期
}

// 禁用互评截止日期选择
const disabledPeerReviewDate = (time) => {
  if (!props.form.due_date) return true
  // 不能选择作业截止日期之前的日期
  return time.getTime() < new Date(props.form.due_date).getTime()
}

const handleClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  emit('update:visible', false)
  emit('close')
}

const handleFileChange = (file, fileList) => {
  emit('update:file-list', fileList)
}

const handleFileRemove = (file, fileList) => {
  emit('update:file-list', fileList)
}

const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate((valid, fields) => {
    if (valid) {
      emit('submit')
    } else {
      console.error('Form validation failed:', fields)
    }
  })
}
</script>

<style scoped>
.assignment-dialog :deep(.el-dialog__body) {
  padding: 0 20px;
}

.form-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.assignment-form {
  padding: 24px 0;
}

.switch-label {
  margin-left: 8px;
  font-size: 14px;
  color: #606266;
}

.info-box {
  margin-top: 8px;
  padding: 12px;
  background: #f0f9ff;
  border-radius: 4px;
  display: flex;
  align-items: flex-start;
  gap: 8px;
  font-size: 13px;
  color: #0369a1;
  line-height: 1.5;
}

.info-box.warning {
  background: #fff7ed;
  color: #9a3412;
}

.info-box .el-icon {
  margin-top: 2px;
}

.upload-btn {
  display: flex;
  align-items: center;
  gap: 4px;
}

.upload-tip {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #64748b;
  font-size: 13px;
  margin-top: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #e5e7eb;
  margin-top: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number.w-full) {
  width: 100%;
}

:deep(.el-upload-list) {
  margin-top: 12px;
}
</style>